package com.taptech.doufu.ui.fragment;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.taptech.doufu.R;
import com.taptech.doufu.constant.EventKey;
import com.taptech.doufu.constant.HomeEnterType;
import com.taptech.doufu.constant.SPKey;
import com.taptech.doufu.constant.SelectBlockTypes;
import com.taptech.doufu.event.BaseEventBusBean;
import com.taptech.doufu.event.EventBusPersonRecommend;
import com.taptech.doufu.ui.activity.BrowseActivity;
import com.taptech.doufu.ui.activity.ChoiceCategoryActivity;
import com.taptech.doufu.ui.activity.NovelCopyRightActivity;
import com.taptech.doufu.ui.activity.NovelRankActivity;
import com.taptech.doufu.ui.activity.UserMemberActivity;
import com.taptech.doufu.ui.activity.story.StoryMainActivity;
import com.taptech.doufu.ui.activity.weex.SimpleWeexActivity;
import com.taptech.doufu.ui.adapter.DFChoiceAdapter;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.constant.HomePageType;
import com.taptech.doufu.constant.UmengEventName;
import com.taptech.doufu.listener.IListScollerState;
import com.taptech.doufu.listener.ToUpOrDownable;
import com.taptech.doufu.bean.DFHomeBannerBean;
import com.taptech.doufu.bean.DFHomeCategoryBean;
import com.taptech.doufu.bean.MarketNovelNoticeBean;
import com.taptech.doufu.bean.choice.ChoiceTopicBean;
import com.taptech.doufu.presenter.home.ChoiceBannerPresenter;
import com.taptech.doufu.presenter.home.ChoiceCategoryPresenter;
import com.taptech.doufu.presenter.home.ChoiceSpeakerPresenter;
import com.taptech.doufu.presenter.home.ChoiceTopicPresenter;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.ui.view.AutoPollAdapter;
import com.taptech.doufu.ui.view.AutoPollRecyclerView;
import com.taptech.doufu.util.CommonUtils;
import com.taptech.doufu.util.ScreenUtil;
import com.taptech.doufu.util.TMAnalysis;
import com.taptech.doufu.ui.view.HomeBannerImageAdapter;
import com.taptech.doufu.ui.view.NetworkImageView;
import com.taptech.doufu.ui.view.PullToRefreshListView;
import com.taptech.doufu.ui.view.TTHomeViewPager;
import com.taptech.doufu.ui.view.viewflow.view.CircleFlowIndicator;
import com.taptech.doufu.ui.view.viewflow.view.HomeViewFlow;
import com.taptech.doufu.util.sp.DiaoBaoSharedPreferences;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 精选页
 */
public class DFChoiceFragment extends HomeBaseFragment
        implements PullToRefreshListView.OnLoadAndRefreshListener,
        ChoiceBannerPresenter.OnHomeBannerView,
        ChoiceCategoryPresenter.OnHomeCategoryView,
        ChoiceSpeakerPresenter.OnHomeSpeakerView,
        ChoiceTopicPresenter.OnHomeTopicView{
    private PullToRefreshListView listView;
    private HomeViewFlow viewFlow;
    private HomeBannerImageAdapter viewFlowAdapter;//轮播图适配器
    private CircleFlowIndicator flowIndicator;
    private List<DFHomeBannerBean> bannerList;
    private List<ChoiceTopicBean> contentAdaList;
    private TTHomeViewPager viewPager;//父类所含有的viewpage，用来控制图片轮转时，触摸事件不回传给父类
    private DFChoiceAdapter listAda;//滑动适配器
    private ImageView ivTop;
    private View rootView;

    private List<MarketNovelNoticeBean> listNotice;
    private boolean isUseCache = true;
    private ChoiceTopicPresenter topicPresenter;
    private ChoiceBannerPresenter bannerPresenter;
    private ChoiceCategoryPresenter categoryPresenter;
    private ChoiceSpeakerPresenter speakerPresenter;

    private IListScollerState iListScollerState;
    private PullToRefreshListView.OnScrollYListener onScrollYListener;

    public void setOnScrollYListener(PullToRefreshListView.OnScrollYListener onScrollYListener) {
        this.onScrollYListener = onScrollYListener;
    }

    public void setiListScollerState(IListScollerState iListScollerState) {
        this.iListScollerState = iListScollerState;
    }

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void openYouthModel(BaseEventBusBean event){
        if (event != null && EventKey.YOUTH_MODEL.equals(event.getTag())) {
            getDataFromNet();
            setYouthModel(true);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void reload(EventBusPersonRecommend eventBusPersonRecommend) {
        if (eventBusPersonRecommend != null && EventBusPersonRecommend.tag.equals(eventBusPersonRecommend.getTag())) {
            getDataFromNet();
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (rootView == null) {
            EventBus.getDefault().register(this);
            rootView = inflater.inflate(R.layout.fragment_dfnovel, null);
            initPresenter();
            initsView(rootView);
            setYouthModel(false);
        }
        return rootView;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initPresenter() {
        topicPresenter = new ChoiceTopicPresenter(getActivity(),this);
        bannerPresenter = new ChoiceBannerPresenter(getActivity(),this);
        categoryPresenter = new ChoiceCategoryPresenter(getActivity(),this);
        speakerPresenter = new ChoiceSpeakerPresenter(getActivity(),this);
    }

    private void loadCache() {
        if (bannerPresenter != null) {
            bannerPresenter.loadBannerCache();
        }
        if (categoryPresenter != null) {
            categoryPresenter.loadCategoryCache();
        }
        if (speakerPresenter != null) {
            speakerPresenter.loadSpeakerCache();
        }
        if (topicPresenter != null) {
            topicPresenter.loadTopicCache();
        }

    }


    private void setYouthModel(boolean update) {
        String pwd = DiaoBaoSharedPreferences.getSharedPreferencesValueToString(SPKey.YOUTH_MODEL_PWD, getActivity(), "");
        if (pwd != null && pwd.length() > 0) {
            listView.setPadding(0,ScreenUtil.dip2px(getActivity(),44)+ScreenUtil.getStatusHeight(getActivity()),0,0);
            listView.removeHeaderView(homeTopEnterView);
        }else{
            if (update) {
                listView.setPadding(0,0,0,0);
                if (homeTopEnterView != null) {
                    listView.addHeaderView(homeTopEnterView);
                }else{
                    addHeadView();
                }
            }
        }
    }


    private void initsView(View rootView) {
        listView = rootView.findViewById(R.id.fragment_dfnovel_list);
        listView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        listView.setRefreshable(true);
        listView.setOnLoadAndRefreshListener(this);
        listView.setMoveListener(new ToUpOrDownable() {
            @Override
            public void moveToUp() {
                ivTop.setVisibility(View.INVISIBLE);
                setToTopVisible(false);
            }

            @Override
            public void moveToDown(int firstVisiblePos) {
                if (firstVisiblePos > 2) {
                    ivTop.setVisibility(View.VISIBLE);
                    setToTopVisible(true);
                }else{
                    ivTop.setVisibility(View.INVISIBLE);
                }
            }
        });
        listView.setOnScrollStateListent(state -> {
            if (iListScollerState != null) {
                iListScollerState.scrollState(state);
            }
        });
        listView.setOnScrollYListener(onScrollYListener);
        ivTop = rootView.findViewById(R.id.fragment_dfnovel_upTop);
        ivTop.setOnClickListener(v -> scrollToTop());
        initsListViewHeadView();
    }
    public void scrollToTop() {
        if (listView != null) {
            listView.setSelection(0);
        }
        if (ivTop != null) {
            ivTop.setVisibility(View.INVISIBLE);

        }
    }

    public void stopSpeaker() {
        if (autoPollRecyclerView != null) {
            autoPollRecyclerView.stop();
        }
    }

    public void startSpeaker() {
        if (autoPollRecyclerView != null) {
            autoPollRecyclerView.start();
        }
    }

    private boolean toTopButtonIsShow = false;

    private void setToTopVisible(boolean visibleAnimation) {
        ObjectAnimator objectAnimators = null;
        AnimatorSet animatorSet = new AnimatorSet();
        if (visibleAnimation) {
            //出现动画
            if (!toTopButtonIsShow) {
                objectAnimators = ObjectAnimator.ofFloat(ivTop, "translationY", ScreenUtil.getScreenHeight(this.getActivity()), 0);
            }
            toTopButtonIsShow = true;
        } else {
            //隐藏动画
            if (toTopButtonIsShow) {
                objectAnimators = ObjectAnimator.ofFloat(ivTop, "translationY", 0, ScreenUtil.getScreenHeight(this.getActivity()) - ivTop.getMeasuredHeight());
            }
            toTopButtonIsShow = false;
        }
        if (objectAnimators != null) {
            animatorSet.setDuration(500);
            animatorSet.playTogether(objectAnimators);
            animatorSet.start();
        }

    }



    /**
     * request server
     */
    private void getDataFromNet() {
        listView.setFull(false);
        listView.setLoadmoreable(true);
        if (topicPresenter != null) {
            String pwd = DiaoBaoSharedPreferences.getSharedPreferencesValueToString(SPKey.YOUTH_MODEL_PWD, getActivity(), "");
            int young = 0;
            if (pwd != null && pwd.length() > 0) {
                young = 1;
            }
            topicPresenter.getTopic(isUseCache,young);
        }
        if (bannerPresenter != null) {
            bannerPresenter.getHomeNovelBanner(isUseCache);
        }
        if (categoryPresenter != null) {
            categoryPresenter.getHomeNovelCategory(isUseCache);
        }
        if (speakerPresenter != null) {
            speakerPresenter.getHomeNovelSpeaker(isUseCache);
        }
    }
    /**
     * 装 headView,包    ，下面
     */
    private void initsListViewHeadView() {
        addHeadView();
        contentAdaList = new ArrayList<>();
        listAda = new DFChoiceAdapter(getActivity(), contentAdaList,listView);
        listView.setAdapter(listAda);
    }


    View homeTopEnterView,headLayRoot;

    private RelativeLayout line1, line2, line3, line4, line5;
    LinearLayout line_bg, llBroadcast, llAutoLayout,layTopLine,layBottomLine;
    private ImageView noticeImg;
    private NetworkImageView[] classifyImag = new NetworkImageView[5];
    private TextView[] classifyName = new TextView[5];
    private AutoPollRecyclerView autoPollRecyclerView;

    private void addHeadView() {
        if (homeTopEnterView == null) {
            homeTopEnterView = LayoutInflater.from(getActivity()).inflate(R.layout.dfhome_viewflow, null);
            llBroadcast =  homeTopEnterView.findViewById(R.id.ll_dfhome_viewflow_broatcast);
            headLayRoot = homeTopEnterView.findViewById(R.id.layRoot);
            viewFlow =  homeTopEnterView.findViewById(R.id.dfhome_exchange_viewflow);
            viewFlow.setLayoutParams(new RelativeLayout.LayoutParams(ScreenUtil.getScreenWidth(getActivity()), (int) (ScreenUtil.getScreenWidth(getActivity())/1.5)));
            flowIndicator =  homeTopEnterView.findViewById(R.id.dfhome_ad_indicator);
            flowIndicator.setVisibility(View.VISIBLE);
            autoPollRecyclerView =  homeTopEnterView.findViewById(R.id.autoPollRecyclerView);
            line_bg =  homeTopEnterView.findViewById(R.id.dfhome_novbel_bg);
            layTopLine = homeTopEnterView.findViewById(R.id.layTopLine);
            layBottomLine = homeTopEnterView.findViewById(R.id.layBottomLine);
            line1 =  homeTopEnterView.findViewById(R.id.dfhome_novel_line1);
            line2 =  homeTopEnterView.findViewById(R.id.dfhome_novel_line2);
            line3 =  homeTopEnterView.findViewById(R.id.dfhome_novel_line3);
            line4 =  homeTopEnterView.findViewById(R.id.dfhome_novel_line4);
            line5 =  homeTopEnterView.findViewById(R.id.dfhome_novel_line5);

            llAutoLayout =  homeTopEnterView.findViewById(R.id.auto_home_novel_layout);
            noticeImg =  homeTopEnterView.findViewById(R.id.dfBL_novel_notice_img);
            classifyName[0] =  homeTopEnterView.findViewById(R.id.dfhome_novel_tv1);
            classifyName[1] =  homeTopEnterView.findViewById(R.id.dfhome_novel_tv2);
            classifyName[2] =  homeTopEnterView.findViewById(R.id.dfhome_novel_tv3);
            classifyName[3] =  homeTopEnterView.findViewById(R.id.dfhome_novel_tv4);
            classifyName[4] =  homeTopEnterView.findViewById(R.id.dfhome_novel_tv5);
            classifyImag[0] =  homeTopEnterView.findViewById(R.id.dfhome_novel_iv1);
            classifyImag[1] =  homeTopEnterView.findViewById(R.id.dfhome_novel_iv2);
            classifyImag[2] =  homeTopEnterView.findViewById(R.id.dfhome_novel_iv3);
            classifyImag[3] =  homeTopEnterView.findViewById(R.id.dfhome_novel_iv4);
            classifyImag[4] =  homeTopEnterView.findViewById(R.id.dfhome_novel_iv5);
            listView.addHeaderView(homeTopEnterView);
        }
    }



    private void initsDefaultCategoryData() {
        line1.setVisibility(View.GONE);
        line2.setVisibility(View.GONE);
        line3.setVisibility(View.GONE);
        line4.setVisibility(View.GONE);
        line5.setVisibility(View.GONE);
        layBottomLine.setVisibility(View.GONE);
    }

    private void initsCategoryData(List<DFHomeCategoryBean> tempCategoryList) {
        initsDefaultCategoryData();
        NetworkImageView ivTemp;
        TextView tvTemp;
        RelativeLayout lineTemp;
        for (int i = 0; (i < 10) && (i < tempCategoryList.size()); i++) {
            if (0 == i) {
                lineTemp = line1;
                ivTemp = classifyImag[0];
                lineTemp.setVisibility(View.VISIBLE);
                tvTemp = classifyName[0];
            } else if (1 == i) {
                lineTemp = line2;
                ivTemp = classifyImag[1];
                tvTemp = classifyName[1];
                lineTemp.setVisibility(View.VISIBLE);
            } else if (2 == i) {
                lineTemp = line3;
                ivTemp = classifyImag[2];
                tvTemp = classifyName[2];
            } else if (3 == i) {
                lineTemp = line4;
                ivTemp = classifyImag[3];
                tvTemp = classifyName[3];
            } else if (4 == i) {
                lineTemp = line5;
                ivTemp = classifyImag[4];
                tvTemp = classifyName[4];
                lineTemp.setVisibility(View.VISIBLE);
            } else {
                lineTemp = null;
                ivTemp = null;
                tvTemp = null;
            }

            if (ivTemp != null) {
                ivTemp.setFullScreen(false);

                setCategoryClickListener(lineTemp,tempCategoryList.get(i));
                ivTemp.setURL(tempCategoryList.get(i).getCover());
                tvTemp.setText(tempCategoryList.get(i).getTitle());
            }
        }
    }

    private void setCategoryClickListener(View clickView, final DFHomeCategoryBean bean) {
        clickView.setOnClickListener(v -> {
            if (bean.getIs_login() && !AccountService.getInstance().isLogin()){
                AccountService.getInstance().jumpToLogin();
                return;
            }

            HashMap<String, String> events = new HashMap<>();
            events.put("title", bean.getTitle());
            events.put("type",bean.getType());
            TMAnalysis.event(getContext(), UmengEventName.JINGXUAN_ENTRANCE,events);
            switch (Integer.parseInt(bean.getType())) {
                case HomeEnterType.CATEGORY: { //分类
                    Intent intent = new Intent();
                    String data = JSON.toJSONString(bean.getList());
                    intent.putExtra(Constant.DATA, data);
                    intent.putExtra(Constant.TITLE, bean.getTitle());
                    intent.setClass(getContext(), ChoiceCategoryActivity.class);
                    startActivity(intent);
                    break;
                }
                case HomeEnterType.RANK:{
                    //排行榜
                    Intent intent = new Intent(getActivity(), NovelRankActivity.class);
                    intent.putExtra(NovelRankActivity.SEX_TYPE, "1");
                    startActivity(intent);
                    break;
                }
                case HomeEnterType.WEEX:{ //weex页面
                    HashMap map = new HashMap();
                    map.put("title", bean.getTitle());
                    map.put("url", bean.getData().toString());
                    String url = "vue/novel/normal/TFNovelView.js";
                    if (!TextUtils.isEmpty(bean.getUrl())) {
                        url = bean.getUrl();
                    }
                    SimpleWeexActivity.startActivity(getContext(),url,map);
                    break;
                }
                case HomeEnterType.IP:{
                    NovelCopyRightActivity.Companion.startActivity(getContext());
                    break;
                }
                case HomeEnterType.MEMBER://
                    UserMemberActivity.Companion.startActivity(getActivity());
                    break;
                case HomeEnterType.WEB:
                    BrowseActivity.startActivity(getActivity(),bean.getUrl());
                    break;
            }

        });
    }


    @Override
    public synchronized void onRefresh() {
        listView.setLoadmoreable(false);
        //重新加载数据
        isUseCache = false;
        getDataFromNet();
    }


    @Override
    public synchronized void loadMore() {
        if (listView.isLoadmoreable()) {
            if (!CommonUtils.isNetWorkConnected(getActivity())) {
                listView.loadMoreComplete();
                listView.setLoadmoreable(true);
                return;
            }

        }
    }


    private void initFlowData() {

        try {
            if (viewFlow != null && bannerList != null) {
                viewFlowAdapter = new HomeBannerImageAdapter(bannerList, getActivity(),HomePageType.SELECTED);
                viewFlow.setAdapter(viewFlowAdapter);
                viewFlow.setmSideBuffer(bannerList.size());// 实际图片张数为size大小
                viewFlow.setTimeSpan(5000);// 图片切换时间间隔
                if (viewPager != null) {
                    viewFlow.setViewPage(viewPager);
                }
                flowIndicator.setViewFlow(viewFlow);
                viewFlow.setFlowIndicator(flowIndicator);
                if (bannerList.size() > 1) {
                    viewFlow.startAutoFlowTimer(); // 启动自动播放
                }
            } else {
                viewFlowAdapter.setData(bannerList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setViewPager(TTHomeViewPager mViewPager) {
        this.viewPager = mViewPager;
    }



    private boolean isAttachActivity = false;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        isAttachActivity = true;
    }

    /**
     * 切换主题
     */
    public void changeThemeWithColorful() {
        if (!isAttachActivity) {
            return;
        }

        if (WeMediaApplication.getInstance().isDayNightMode_Night) {
            changeDarkViewBg();
        } else {
            changeDayViewBg();
        }
        if (listAda != null) {
            listAda = new DFChoiceAdapter(getActivity(), contentAdaList,listView);
            listView.setAdapter(listAda);
        }
        if (viewFlowAdapter != null) {
            initFlowData();
        }
        listView.changeBgView();
    }

    private void changeDayViewBg() {
        line_bg.setBackground(getResources().getDrawable(R.color.white));
        for (int i = 0; i < classifyName.length; i++) {
            classifyName[i].setTextColor(getResources().getColor(R.color.text_color_2));
            classifyImag[i].setBackgroundColor(getResources().getColor(R.color.transparent_background));
            classifyImag[i].setAlpha(1.0f);
        }
        noticeImg.setAlpha(1.0f);
        llBroadcast.setBackgroundColor(getResources().getColor(R.color.white));
        llAutoLayout.setBackgroundResource(R.drawable.shape_roundrectangle);
    }

    private void changeDarkViewBg() {
        line_bg.setBackgroundColor(getResources().getColor(R.color.fg_dark));
        for (int i = 0; i < classifyName.length; i++) {
            classifyName[i].setTextColor(getResources().getColor(R.color.text_dark));
            classifyImag[i].setBackgroundColor(getResources().getColor(R.color.fg_dark));
            classifyImag[i].setAlpha(Constant.imagViewAlpha);
        }
        noticeImg.setAlpha(Constant.imagViewAlpha);
        llBroadcast.setBackgroundColor(getResources().getColor(R.color.fg_dark));
        llAutoLayout.setBackgroundResource(R.drawable.shape_roundrectangle_dark);
    }


    @Override
    public void fetchData() {
        loadCache();
        getDataFromNet();
    }


    @Override
    public void onTopicNext(List<ChoiceTopicBean> list, boolean isCache) {
        contentAdaList = list;
        try {
            boolean showRecommend = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean("sp_personal_recommend", getContext(), true);
            if (!showRecommend &&  contentAdaList.size()>0) {
                if (contentAdaList.get(contentAdaList.size() - 1).getType() == SelectBlockTypes.RECOMMEND) {
                    contentAdaList.remove(contentAdaList.size() - 1);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (listAda != null && isCache) {
            listAda.refrushList(contentAdaList);
        }else{
            listAda = new DFChoiceAdapter(getActivity(), contentAdaList,listView);
            listView.setAdapter(listAda);
        }
        onRefreshComplete();
    }

    @Override
    public void onTopicError() {
        onRefreshComplete();
    }


    private void onRefreshComplete() {
        /**
         * 刷新动画做延迟处理
         */
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(1000);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (listView != null) {
                                listView.onRefreshComplete();
                            }
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }



    @Override
    public void onBannerNext(List<DFHomeBannerBean> list, boolean isCache) {
        if (list != null && list.size()>0) {
            addHeadView();
            bannerList = list;
            initFlowData();
        }
    }


    @Override
    public void onCategoryNext(List<DFHomeCategoryBean> list, boolean isCache) {
        if (list != null) {
            initsCategoryData(list);
        }
    }

    @Override
    public void onSpeakerNext(List<MarketNovelNoticeBean> list, boolean isCache) {
        if (list != null) {
            listNotice = list;
            if (listNotice != null && listNotice.size() > 0) {
                if (!TextUtils.isEmpty(listNotice.get(0).getMsg())) {
                    llBroadcast.setVisibility(View.VISIBLE);
                    AutoPollAdapter adapter = new AutoPollAdapter(getActivity(), listNotice,HomePageType.SELECTED);
                    autoPollRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
                    autoPollRecyclerView.setAdapter(adapter);
                    autoPollRecyclerView.start();
                } else {
                    llBroadcast.setVisibility(View.GONE);
                }
            } else {
                llBroadcast.setVisibility(View.GONE);
            }
        }
    }
}
